import cv2
import numpy as np

# 统一缩放到最大宽高800
def resize_keep_ratio(img, max_w=800, max_h=800):
    h, w = img.shape[:2]
    ratio = min(max_w / w, max_h / h, 1.0)
    new_w, new_h = int(w * ratio), int(h * ratio)
    return cv2.resize(img, (new_w, new_h))

# 读取照片，推荐文件名为 me.jpg（可自行替换）
filename = 'me.jpg'
img = cv2.imread(filename)

if img is None:
    raise FileNotFoundError(f'找不到图片文件 {filename} ，请确保它位于当前目录！')

# ------ 1. 素描效果 ------
# 转灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯模糊
gray_blur = cv2.GaussianBlur(gray, (21, 21), sigmaX=0, sigmaY=0)
# 利用反色做线稿融合
sketch = cv2.divide(gray, 255-gray_blur, scale=256)
sketch_small = resize_keep_ratio(sketch)

# ------ 2. 漫画/卡通风效果 ------
# 彩色平滑处理
color = cv2.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)
# 边缘检测
edges = cv2.adaptiveThreshold(gray, 255, 
                              cv2.ADAPTIVE_THRESH_MEAN_C, 
                              cv2.THRESH_BINARY, blockSize=9, C=2)
# 彩色和边缘叠加
cartoon = cv2.bitwise_and(color, color, mask=edges)
cartoon_small = resize_keep_ratio(cartoon)

# ------ 显示所有结果 ------
cv2.imshow('① 素描风效果（缩放）', sketch_small)
cv2.imshow('② 卡通漫画滤镜（缩放）', cartoon_small)
print('已自动缩放，按任意键关闭所有窗口...')
cv2.waitKey(0)
cv2.destroyAllWindows()
